package com.thingple.nfc;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Parcelable;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class NdefMessageWrapper {
    public List<List<byte[]>> list = new ArrayList<>();
    public String content;

    public NdefMessageWrapper(Intent intent) {
        resolve(intent);
        resolveContent();
    }

    private void resolve(Intent intent) {
        Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (messages == null) {
            return ;
        }
        for (Parcelable p : messages) {
            List<byte[]> records = new ArrayList<>();
            NdefMessage msg = (NdefMessage) p;
            for (NdefRecord record : msg.getRecords()) {
                if (record == null) {
                    continue;
                }
                byte[] payload = record.getPayload();
                if (payload == null) {
//                    continue;
                    payload = new byte[0]; // TODO 默认空字节码
                }
                records.add(payload);
            }
            list.add(records);
        }
    }

    private void resolveContent() {

        StringBuilder sb = new StringBuilder();
        for (List<byte[]> group : list) {
            for (byte[] bs : group) {
                String c = new String(bs, StandardCharsets.UTF_8);
                sb.append(c).append("\r\n");
            }
        }
        content = sb.toString();
    }
}
